<template>
  <div>
    <!-- el过渡动画 -->
    <transition name="el-fade-in-linear">
      <!-- 导航栏 -->
      <!-- v-show 指令来根据 toolbar.visible 属性的值来控制其显示或隐藏-->
      <!-- 鼠标进入元素时，hoverEnter 被设置为 true -->
      <div v-show="true"
           class="toolbar-content myBetween">
        <div class="toolbar-title">
          <h2 @click="$router.push({path: '/admin'})">吉首大学课程管理系统</h2>
        </div>

        <div>
          <ul class="scroll-menu">
            <!-- 学生的一些界面 -->
            <li @click="$router.push({path: '/course'})" v-if="role === 1">
              <div class="my-menu">
                <span>查看课程</span>
              </div>
            </li>
            <li @click="$router.push({path: '/course-select'})" v-if="role === 1">
              <div class="my-menu">
                <span>选课中心</span>
              </div>
            </li>
            <li @click="$router.push({path: '/course-comment'})" v-if="role === 1">
              <div class="my-menu">
                <span>课程评价</span>
              </div>
            </li>
            <!-- 老师的界面 -->
            <li @click="$router.push({path: '/course-manage-teacher'})" v-if="role === 2">
              <div class="my-menu">
                <span>所授课程</span>
              </div>
            </li>
            <li @click="$router.push({path: '/course-comment-teacher'})" v-if="role === 2">
              <div class="my-menu">
                <span>课程评价</span>
              </div>
            </li>

            <li>
              <el-dropdown placement="bottom">
                <el-avatar :size="36"
                           :src="( !$common.isEmpty($store.state.currentUser) ? $store.state.currentUser.avatar : 'https://qiniu.suqi.store/suqi.jpg' )"
                           class="user-avatar"
                           style="margin-top: 12px">
                </el-avatar>

                <el-dropdown-menu slot="dropdown">
                  <div v-if="!$common.isEmpty($store.state.currentUser) ">
                    <el-dropdown-item v-if="role === 1">学生:{{ $store.state.currentUser.name }}</el-dropdown-item>
                    <el-dropdown-item v-if="role === 2">老师:{{ $store.state.currentUser.name }}</el-dropdown-item>
                    <el-dropdown-item v-if="role === 3">{{ $store.state.currentUser.name }}</el-dropdown-item>
                    <el-dropdown-item
                      @click.native="getStudentInfo();" v-if="role === 1">
                      <i aria-hidden="true" class="fa fa-sign-out"></i> <span>个人中心</span>
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click.native="getTeacherInfo();" v-if="role === 2">
                      <i aria-hidden="true" class="fa fa-sign-out"></i> <span>个人中心</span>
                    </el-dropdown-item>
                    <el-dropdown-item
                      @click.native="toLogout()" v-if="role === 1 || role === 2 || role === 3">
                      <i aria-hidden="true" class="fa fa-sign-out"></i> <span>退出</span>
                    </el-dropdown-item>
                  </div>
                </el-dropdown-menu>
              </el-dropdown>
            </li>
          </ul>
        </div>
      </div>
    </transition>
    <el-dialog :visible.sync="studentInfoDialogVisible" title="学生个人中心" width="50%">
      <el-form ref="studentFormRef" :model="studentInfoForm" :rules="studentRules">
        <el-form-item :label-width="formLabelWidth" label="姓名:" prop="name">
          <el-input v-model="studentInfoForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="学号:" prop="studentNum">
          <el-input v-model="studentInfoForm.studentNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="已修学分:">
          <span>{{studentInfoForm.learnCredits}}</span>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="年级:" prop="grade">
          <el-select v-model="studentInfoForm.grade" placeholder="请选择">
            <el-option label="大一" value="1"></el-option>
            <el-option label="大二" value="2"></el-option>
            <el-option label="大三" value="3"></el-option>
            <el-option label="大四" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="头像">
          <ImageUpload ref="studentImage" :limit="1" @update-file-list="handleUpdateStudentAvatar"></ImageUpload>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="修改密码:" prop="password">
          <el-button @click="showStudentPasswordInput = !showStudentPasswordInput">修改密码</el-button>
          <el-input v-if="showStudentPasswordInput" v-model="studentInfoForm.password" type="password" autocomplete="off" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="studentInfoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveStudentInfo()">保存</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="teacherInfoDialogVisible" title="老师个人中心" width="50%">
      <el-form :rules="teacherRules" ref="teacherFormRef" :model="teacherInfoForm">
        <el-form-item :label-width="formLabelWidth" label="姓名" prop="name">
          <el-input v-model="teacherInfoForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="工号" prop="teacherNum">
          <el-input v-model="teacherInfoForm.teacherNum" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="课程数">
          <span>{{teacherInfoForm.courseNum}}</span>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth" label="头像">
          <ImageUpload ref="teacherImage" :limit="1" @update-file-list="handleUpdateTeacherAvatar"></ImageUpload>
        </el-form-item>
        <!-- 新增修改密码项 -->
        <el-form-item :label-width="formLabelWidth" label="修改密码:" prop="password">
          <el-button @click="showTeacherPasswordInput = !showTeacherPasswordInput">修改密码</el-button>
          <el-input v-if="showTeacherPasswordInput" v-model="teacherInfoForm.password" type="password" autocomplete="off" placeholder="请输入新密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="teacherInfoDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveTeacherInfo()">保存</el-button>
      </span>
    </el-dialog>
    <div class="centered-content">
      <router-view></router-view>
    </div>
  </div>
</template>

<script>
import {userLogout} from "@/apis/user";
import ImageUpload from "@/common/ImageUpload.vue";
import {getTeacherDetail, updateTeacherInfo} from "@/apis/teacher";
import {getStudentDetail, updateStudentInfo} from "@/apis/student";

export default {
  components: {ImageUpload},
  data() {
    return {
      studentRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度应在 2 到 20 个字符之间', trigger: 'blur' }
        ],
        studentNum: [
          { required: true, message: '请输入学号', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{4,20}$/, message: '学号格式不正确', trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请选择年级', trigger: 'change' }
        ],
        password: [
          { min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur' }
        ]
      },
      teacherRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '姓名长度应在 2 到 20 个字符之间', trigger: 'blur' }
        ],
        teacherNum: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{4,20}$/, message: '工号格式不正确', trigger: 'blur' }
        ],
        password: [
          { min: 6, max: 20, message: '密码长度应在 6 到 20 个字符之间', trigger: 'blur' }
        ]
      },

      toolButton: false,
      studentInfoDialogVisible: false, // 控制个人中心的显示
      showStudentPasswordInput: false,  // 控制密码输入框的显示
      studentInfoForm: { // 编辑表单的数据模型
        studentNum: '',
        avatarUrl: '',
        name: '',
        learnCredits: '',
        grade: '',
        password: ''
      },
      teacherInfoDialogVisible: false, // 控制个人中心的显示
      showTeacherPasswordInput: false,  // 控制密码输入框的显示
      teacherInfoForm: { // 编辑表单的数据模型
        teacherNum: '',
        avatarUrl: '',
        name: '',
        courseNum: '',
        password: ''
      },
      formLabelWidth: '120px', // 表单标签宽度
    }
  },
  // Vue.js 组件中的 mounted 钩子函数。mounted 钩子在 Vue 实例挂载后调用，进行初始化操作，即当 Vue 实例的 DOM 元素被插入到页面中后执行
  mounted() {
  },
  //Vue.js 组件的 destroyed 钩子函数中，用于在组件销毁时进行一些清理工作
  destroyed() {
  },
  //监听代码部分
  watch: {
  },
  //在实例创建完成后被立即调用。在这一阶段，实例已经完成数据观测、属性和方法的运算，但是挂载阶段还未开始。可以在这里进行数据初始化、异步请求等操作。
  created() {
  },
  computed: {//计算派生数据的属性
    role() {
      return Number(this.$store.state.role);
    }
  },
  methods: {
    // 获取学生个人信息
    getStudentInfo(){
      getStudentDetail().then(res => {
        this.studentInfoDialogVisible = true; // 打开编辑对话框
        this.studentInfoForm = res.data.data;
        this.$nextTick(() => {
          this.$refs.studentImage.fileList = [];

          if (res.data.avatarUrl !== null) {

            if (this.$refs.studentImage) {
              this.$refs.studentImage.setFileList(this.studentInfoForm.avatarUrl);
            }

          }
        });
      }).catch(error => {
        this.$message.error("获取课程详情失败");
      });
    },
    // 获取老师个人信息
    getTeacherInfo(){
      getTeacherDetail().then(res => {
        this.teacherInfoDialogVisible = true; // 打开编辑对话框
        this.teacherInfoForm = res.data.data;
        this.$nextTick(() => {
          this.$refs.teacherImage.fileList = [];

          if (res.data.avatarUrl !== null) {

            if (this.$refs.teacherImage) {
              this.$refs.teacherImage.setFileList(this.teacherInfoForm.avatarUrl);
            }

          }
        });
      }).catch(error => {
        this.$message.error("获取课程详情失败");
      });
    },
    handleUpdateStudentAvatar(newFileList) {
      // 使用传递过来的 fileList 更新父组件的 parentFileList
      // 遍历 newFileList 数组
      newFileList.forEach(file => {
        // 将每个文件的 URL 添加到 imageUrls 数组中
        this.studentInfoForm.avatarUrl = file.url;
      });
    },
    handleUpdateTeacherAvatar(newFileList) {
      // 使用传递过来的 fileList 更新父组件的 parentFileList
      // 遍历 newFileList 数组
      newFileList.forEach(file => {
        // 将每个文件的 URL 添加到 imageUrls 数组中
        this.teacherInfoForm.avatarUrl = file.url;
      });
    },
    saveStudentInfo() {
      this.$refs.studentFormRef.validate((valid) => {
        if (valid) {
          if (!this.$common.isEmpty(this.studentInfoForm.password)) {
            this.studentInfoForm.password = this.$common.encrypt(this.studentInfoForm.password);
          }
          updateStudentInfo(this.studentInfoForm).then(res=>{
            if (res.data.code === 1){
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.studentInfoDialogVisible = false;
            }
          })
        } else {
          this.$message.error('表单中有错误，请修正后再尝试保存');
          return false;
        }
      });
    },
    saveTeacherInfo() {
      this.$refs.teacherFormRef.validate((valid) => {
        if (valid) {
          if (!this.$common.isEmpty(this.teacherInfoForm.password)) {
            this.teacherInfoForm.password = this.$common.encrypt(this.teacherInfoForm.password);
          }
          updateTeacherInfo(this.teacherInfoForm).then(res=>{
            if (res.data.code === 1){
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.teacherInfoDialogVisible = false;
            }
          })
        } else {
          this.$message.error('表单中有错误，请修正后再尝试保存');
          return false;
        }
      });
    },
    //退出
    toLogout() {
      if (!this.$common.isEmpty(this.$store.state.currentUser)) {//当前为管理员登录，调用管理员退出函数
        userLogout().then((result) => {
          if (result.data.code === 1) {//退出成功
            // 移除用户角色设置
            this.$store.commit("loadRole", -1)
            //移除令牌信息
            this.$store.commit("removeJwtToken");
            // 移除用户信息
            this.$store.commit("loadCurrentUser", {});
            //重新加载
            window.location.reload();
          } else {
            this.$message({
              message: result.data.msg,
              typeIdList: "error"
            });
          }
        })
      }
    }
  }
}
</script>

<style scoped>
.centered-content {
  background-color: #daeabd;
  display: flex; /* 设置为flex布局 */
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
  height: 100vh; /* 设置父容器的高度，100vh表示100%的视口高度 */
}


.toolbar-content {
  width: 100%;
  height: 60px;
  color: var(--white);
  /* 固定位置，不随滚动条滚动 */
  position: fixed;
  z-index: 100;
  /* 禁止选中文字 */
  user-select: none;
  transition: all 0.3s ease-in-out;
  background: var(--translucent);
  box-shadow: 0 1px 3px 0 rgba(0, 34, 77, 0.05);
}



.toolbar-title {
  margin-left: 30px;
  cursor: pointer;
}


.scroll-menu {
  margin: 0 25px 0 0;
  display: flex;
  justify-content: flex-end;
  padding: 0;
}

.scroll-menu > li {
  list-style: none;
  margin: 0 12px;
  font-size: 17px;
  height: 60px;
  line-height: 60px;
  position: relative;
  cursor: pointer;
}

.scroll-menu > li:hover .my-menu span {
  color: var(--themeBackground);
}

.scroll-menu > li:hover .my-menu i {
  color: var(--themeBackground);
  animation: scale 1.5s ease-in-out infinite;
}

.scroll-menu > li .my-menu:after {
  content: "";
  display: block;
  position: absolute;
  bottom: 0;
  height: 6px;
  background-color: var(--themeBackground);
  width: 100%;
  max-width: 0;
  transition: max-width 0.25s ease-in-out;
}

.scroll-menu > li:hover .my-menu:after {
  max-width: 100%;
}

.my-setting i {
  padding: 5px;
}

.my-setting i:hover {
  color: var(--themeBackground);
}

.cd-top {
  background: var(--toTop) no-repeat center;
  position: fixed;
  right: 5vh;
  top: -900px;
  z-index: 99;
  width: 70px;
  height: 900px;
  background-size: contain;
  transition: all 0.5s ease-in-out;
  cursor: pointer;
}

</style>
